//
// Created by Administrator on 2022/10/21.
//

//使用数组实现栈结构,称为顺序栈,使用两栈共享空间,数组的首端和末端分别为两个栈的栈底

#include <stdio.h>
#include <malloc.h>

#define MAXSIZE 10
#define ERROR 0
#define OK 1
typedef int ElementType;
typedef int Status;
typedef struct {
    ElementType data[MAXSIZE];
    int top1; /* 表示栈1顶指针 */
    int top2; /* 表示栈2顶指针 */
}sqStack;
//初始化一个栈结构
sqStack initSqStack(){
    sqStack* stack= (sqStack*)malloc(sizeof(sqStack));
    (stack)->top1=-1;
    (stack)->top2=MAXSIZE;
    return *stack;
}
//压栈操作,放入一个元素到栈中
Status push(sqStack *stack,ElementType e,int stackNum){
    if(stack->top2-stack->top1==1){
        return ERROR;  // 栈已满
    }
    if(stackNum==1) {
        (*stack).data[++(stack->top1)] = e;
        return OK;
    }
    if(stackNum==2){
        (*stack).data[--(stack->top2)] =e;
        return OK;
    }

}

//出栈操作,删除并返回栈顶元素
Status pop(sqStack *stack,ElementType *e,int stackNum){
    if((stack->top1==-1&&stackNum==1)||(stackNum==2&&stack->top2==MAXSIZE)){
        return ERROR; //栈1或者2为空
    }
    if(stackNum==1) {
        *e =  (*stack).data[(stack->top1)--] ;
        return OK;
    }
    if(stackNum==2){
        *e = (*stack).data[(stack->top2)++];
        return OK;
    }


}
//显示栈中的所有元素
void showSqStack(sqStack stack,int stackNum){
    if(stackNum==1){
        int length= stack.top1;
        for (int i = 0; i <= length; ++i) {
            printf("%d\n",stack.data[i]);
        }
    }
    if(stackNum==2){
        int length= stack.top2;
        for (int i = MAXSIZE-1; i >= length; --i) {
            printf("%d\n",stack.data[i]);
        }
    }
}

void main(){
    sqStack stack=initSqStack();
    int tmp;
    printf("压栈:");
    push(&stack,0,1);
    push(&stack,1,1);
    push(&stack,2,1);
    push(&stack,3,1);
    push(&stack,4,1);
    push(&stack,0,2);
    push(&stack,1,2);
    push(&stack,2,2);
    push(&stack,3,2);
    push(&stack,4,2);
    pop(&stack,&tmp,2);
    push(&stack,999,2);
    printf("栈1:");
    showSqStack(stack,1);
    printf("栈2:");
    showSqStack(stack,2);


}